<?php
/**
 * @author 	PrestaLive <contact@prestalive.com>
 * @copyright  2011 PrestaLive
 * @version  	1.0 
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */
class ConceptClass extends ObjectModel
{
	public		$id;
	public		$field;
	public		$active = true;
	public 		$display = false;
	public		$id_pl_at_tab;
	public		$active_attribute = false;
	//lang
	public      $name;
	public      $description;
	public      $value;
	
	protected 	$fieldsRequired = array('field');
 	protected 	$fieldsSize = array('field' => '255');
// 	protected 	$fieldsValidate = array('field' => 'isOrderBy');
	protected	$fieldsRequiredLang = array('name');
	protected	$fieldsSizeLang = array('name' => 128);
	protected	$fieldsValidateLang = array('name' => 'isGenericName', 'description' => 'isString', 'value' => 'isString');
	
	protected 	$table = 'pl_at_attribute';
	protected	$identifier = 'id_pl_at_attribute';
	
	/**
	 * Prepare fields for ObjectModel class (add, update)
	 * All fields are verified (pSQL, intval...)
	 * @view ObjectModel::getFields()
	 *
	 * @return array All object fields
	 */
	public	function getFields()
	{
	 	parent::validateFields(false);
		$fields['field'] = $this->field;
		$fields['active'] = (int)($this->active);
		$fields['active_attribute'] = (int)($this->active_attribute);
		$fields['display'] = (int)($this->display);
		$fields['id_pl_at_tab'] = (int)$this->id_pl_at_tab;
		return $fields;
	}

	/**
	 * Check then return multilingual fields for database interaction
	 *
	 * @return array Multilingual fields
	 */
	public function getTranslationsFieldsChild()
	{
//		parent::validateFieldsLang();
//		return parent::getTranslationsFields(array('name', 'description', 'value'));
		$fieldsArray = array('name', 'description', 'value');
		$fields = array();
		$languages = Language::getLanguages(false);
		$defaultLanguage = Configuration::get('PS_LANG_DEFAULT');
		foreach ($languages as $language)
		{
			$fields[$language['id_lang']]['id_lang'] = $language['id_lang'];
			$fields[$language['id_lang']][$this->identifier] = (int)($this->id);

			foreach ($fieldsArray as $field)
			{
				if (!Validate::isTableOrIdentifier($field))
					die(Tools::displayError());

				/* Check fields validity */
				if (isset($this->{$field}[$language['id_lang']]) AND !empty($this->{$field}[$language['id_lang']]))
					$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$language['id_lang']], true);
				elseif (in_array($field, $this->fieldsRequiredLang))
					$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$defaultLanguage]);
				else
					$fields[$language['id_lang']][$field] = '';

			}
			
			$fields[$language['id_lang']]['description'] = (isset($this->description[$language['id_lang']])) ? pSQL($this->description[$language['id_lang']], true) : '';
			$fields[$language['id_lang']]['value'] = (isset($this->value[$language['id_lang']])) ? pSQL($this->value[$language['id_lang']], true) : '';
		}
		return $fields;
	}
	
	/**
	 * Delete current object from database
	 * @view ObjectModel::delete()
	 * 
	 * return boolean Deletion result
	 */
	public function delete()
	{
		if (!Db::getInstance()->Execute('ALTER TABLE `'._DB_PREFIX_.'product_lang` DROP COLUMN `'.$this->field.'`'))
			return false;
		return parent::delete();
	}
	
	/**
	 * Delete several objects from database
	 * @view ObjectModel::deleteSelection()
	 *
	 * return boolean Deletion result
	 */
	public function deleteSelection($selection)
	{
		foreach ($selection AS $id) {
			$field = Db::getInstance()->getValue('SELECT field FROM `'._DB_PREFIX_.$this->table.'` WHERE  `'.$this->identifier.'`='.$id);
			$this->field = $field;
			$this->id = (int)($id);
			$this->delete();
		}
		return parent::delete();
	}
	
	/**
	 * Return available attributes by tab id
	 *
	 * @param integer $tabId Tab ID
     * @param boolean $active return only active tabs
	 * @return array Tabs
	 */
	public static function getAttributesByTabId($tabId, $active = false, $active_attribute = false)
	{
		global $cookie;
		return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT al.name, a.field, a.display, al.value
		FROM `'._DB_PREFIX_.'pl_at_attribute` a
		LEFT JOIN `'._DB_PREFIX_.'pl_at_attribute_lang` al ON (a.`id_pl_at_attribute` = al.`id_pl_at_attribute` AND al.`id_lang` = '.(int)$cookie->id_lang.')
		WHERE 1
		'.($active_attribute ? 'AND a.active_attribute = 1' : 'AND a.active_attribute = 0').'
		AND a.id_pl_at_tab = '.$tabId.'
		'.($active ? 'AND a.active = 1' : '').'
		ORDER BY al.name ASC');
	}
	
	/**
	 * Return available attributes
	 *
     * @param boolean $active return only active tabs
	 * @return array Tabs
	 */
	public static function getAttributes($active = false)
	{
		global $cookie;
		return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
		SELECT a.field
		FROM `'._DB_PREFIX_.'pl_at_attribute` a
		LEFT JOIN `'._DB_PREFIX_.'pl_at_attribute_lang` al ON (a.`id_pl_at_attribute` = al.`id_pl_at_attribute` AND al.`id_lang` = '.(int)$cookie->id_lang.')
		WHERE 1
		'.($active ? 'AND a.active = 1' : '').'
		ORDER BY al.name ASC');
	}
	
	/**
	 * process Update Attributes 
	 * 
	 * @param int $id_product
	 * @return void
	 */
	public static function processUpdateAttribute($productId)
	{
		foreach (self::getAttributes(true) as $attribute) {
			$fieldsArray[] = $attribute['field'];
		}
		
		$languages = Language::getLanguages(false);	// All languages id
		foreach ($languages AS $language) {
			$fields[$language['id_lang']]['id_lang'] = (int)$language['id_lang'];
			foreach ($fieldsArray as $field) {
				if (isset($_POST[$field.'_'.$language['id_lang']])) {
					$fields[$language['id_lang']][$field] = pSQL($_POST[$field.'_'.$language['id_lang']], true);
				}					
			}
		}
		
		foreach ($fields as $field) {
			$where_lang = '`id_product` = '.$productId.' AND `id_lang` = '.(int)$field['id_lang'];
			$result = Db::getInstance()->autoExecute(_DB_PREFIX_.'product_lang', $field, 'UPDATE', $where_lang);
		}
	}
	
	/**
	 * Get all value attributes language for this product
	 * 
	 * @param unknown_type $productId
	 * @param unknown_type $field
	 */
	public static function getValueAttributes($productId, $field) 
	{
		$result = Db::getInstance()->ExecuteS('
			SELECT '.$field.', id_lang 
			FROM `'._DB_PREFIX_.'product_lang` 
			WHERE `id_product` = '.$productId);
		if ($result)
			foreach ($result AS $row) 
				$fieldValue[(int)$row['id_lang']] = $row[$field];
		return $fieldValue;
	}
	
	/**
	 * Get all value attributes language for all product
	 * 
	 * @param unknown_type $productId
	 * @param unknown_type $field
	 */
	public static function getValueAttributesForAllProduct() 
	{
		$result = Db::getInstance()->ExecuteS('
			SELECT value, id_lang 
			FROM `'._DB_PREFIX_.'product_lang` 
			WHERE `id_product` = '.$productId);
		if ($result)
			foreach ($result AS $row) 
				$fieldValue[(int)$row['id_lang']] = $row[$field];
		return $fieldValue;
	}
}